package com.kaohe.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.kaohe.domain.Category;
import com.kaohe.domain.PageBean;
import com.kaohe.service.CategoryService;
import com.sun.org.apache.bcel.internal.util.SecuritySupport;

@WebServlet("/categoryServlet")
public class CategoryServlet extends BaseServlet {
	
	CategoryService service=new CategoryService();
	// 查询
	public String cquery(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		// 1.接收pageNumber
		String pageNumber = request.getParameter("pageNumber");
		// 2.设置pageSize
		int pageSize = 3;
		// 3.封装pageBean
		PageBean<Category> pb = new PageBean<>();
		pb.setPageNumber(Integer.parseInt(pageNumber));
		pb.setPageSize(pageSize);
		// 4.调用service处理
		PageBean<Category> cpb = service.cquery(pb);
		// 5.存储请求域
		request.setAttribute("pb", cpb);
		// 6.请求转发
		return "/admin/category_list.jsp";
	}
	//添加
	public String addcategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		try {
			// 1.接收参数
			Map<String, String[]> map = request.getParameterMap();
			// 2.封装数据
			Category category = new Category();
			BeanUtils.populate(category, map);
			// 3.调用service
			service.addcategory(category);
			// 4.重定向查询
			response.sendRedirect(request.getContextPath() + "/categoryServlet?method=cquery&pageNumber=1");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	//修改--跳转页面
	public String toUpdateCategory(HttpServletRequest request, HttpServletResponse response) throws IOException{
		//接收参数
		String cid = request.getParameter("cid");
		//调用
		Category cup=service.toUpdateCategory(cid);
		//存储数据
		request.setAttribute("category", cup);
		//请求转发
		return "/admin/category_update.jsp";
	}				
	//修改数据
	public String update(HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
			//接收参数
			Map<String, String[]> map = request.getParameterMap();
			//封装
			Category category=new Category();
			BeanUtils.populate(category, map);
			//调用
			service.update(category);
			//重定向
			response.sendRedirect(request.getContextPath() + "/categoryServlet?method=cquery&pageNumber=1");
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;	
	}
	//删除
	public String decategory(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		//接收cid
		String cid = request.getParameter("cid");
		//调用
		service.decategory(cid);
		//重定向
		response.sendRedirect(request.getContextPath() + "/categoryServlet?method=cquery&pageNumber=1");

		return null;	
	}
		
}
